// miniprogram/pages/add/sign.js
var QQMapWX = require('../../util/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
var qqmapsdk;
const { dateFMT, getWeek } = require('../../util/helper');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    longitude: "",
    latitude: "",
    date: dateFMT(new Date(), 'Y-M-D'),
    time: dateFMT(new Date(), 'h:m'),
    markInfo: '',
    currentRegion: {},
    nearList: [],
    keyword: '',
    address: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: '3V5BZ-43B3K-XCOJT-ABRUV-JVZ7J-MTFTG'
    });
    wx.showLoading({
      title: '加载中'
    });
    this.mapCtx = wx.createMapContext('map')
    this.getLocationAuth();
  },
  getLocationAuth: function () {
    let page = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              page.getCurrentLoction();
            }
          })
        } else {
          page.getCurrentLoction();
        }
      },
      fail(res){
        wx.hideLoading({});
        wx.showToast({
          title: '获取授权失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  getCurrentLoction: function () {
    const self = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude
          },
          success: function (res) {
            wx.hideLoading({});
            self.setData({
              latitude: latitude,
              longitude: longitude,
              currentRegion: res.result.address_component,
              address: res.result.address,
            })
            // 调用接口
            // self.nearby_search();
          },
          fail:function(res){
            console.log(res);
            wx.showToast({
              title: '获取当前位置失败',
              icon: 'none',
              duration: 2000
            })
          }
        });
      },
      fail(err) {
        wx.hideLoading({});
        wx.showToast({
          title: '定位失败',
          icon: 'none',
          duration: 1500
        })

      }
    })
  },

  //监听拖动地图，拖动结束根据中心点更新页面
  mapChange: function (e) {
    let self = this;
    if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
      self.mapCtx.getCenterLocation({
        success: function (res) {
          self.setData({
            nearList: [],
            latitude: res.latitude,
            longitude: res.longitude,
          })
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: function (res) {
              self.setData({
                currentRegion: res.result.address_component,
                address: res.result.address,
                addressReference: res.result.address_reference,
              })
              // 调用接口
            },
          });
        }
      })
    }
  },
  requestNotice: function (e) {
    let page = this;
    wx.requestSubscribeMessage({
      tmplIds: ['Y0DtS_uctqpi9Bzwcu81YAY5AX-L6wQ6o3UtyQX-5u8', 'ZX4URTu5Mi3j7Zy1w9jyZFvdFDOFJ7ZQXeQb6cx4YC4'],
      success(res) {
      },
      fail(res){
        console.log(res)
      }
    })
  },

  bindsbumit: function (e) {
    wx.showLoading({
      title: '提交中...',
    })
    let userInfo = e.detail.userInfo;
    let { longitude,
      latitude,
      date,
      time,
      markInfo,
      currentRegion, address, } = this.data;
    if (!longitude || !latitude || !date || !time || !address) {
      wx.showToast({
        title: '获取信息失败',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    let week = getWeek(date);
    let dateArray = date.split("-");
    let timeArray = time.split(":");
    let appointTime = new Date(dateArray[0], parseInt(dateArray[1] - 1), parseInt(dateArray[2]), parseInt(timeArray[0]), parseInt(timeArray[1]), 0);
    if (appointTime < new Date()) {
      wx.showToast({
        title: '约定时间错误',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    let { nickName, avatarUrl } = userInfo;
    const db = wx.cloud.database();
    db.collection('todos').add({
      data: {
        longitude,
        latitude,
        date,
        time,
        markInfo,
        currentRegion, address,
        nickName, avatarUrl,
        createTime: db.serverDate(),
        inviteCount: 0,
        invite: [],
        appointTime,
        week,
        openid: app.globalData.openid
      },
      success: function (res) {
        wx.hideLoading()
        // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
        wx.navigateTo({
          url: '../list/detial?todoid=' + res._id,
        })
      },
      fail(e) {
        console.log(e)
      }
    })
  },
  markInput: function (e) {
    this.setData({ markInfo: e.detail.value })
  },
  searchAddres: function (e) {
    let value = e.detail.value;
    var self = this;
    wx.hideLoading();
    wx.showLoading({
      title: '加载中'
    });
    // 调用接口
    qqmapsdk.search({
      keyword: value,  //搜索关键词
      location: self.data.latitude + ',' + self.data.longitude,
      page_size: 20,
      page_index: 1,
      success: function (res) { //搜索成功后的回调
        var sug = [];
        for (var i = 0; i < res.data.length; i++) {
          sug.push({ // 获取返回结果，放到sug数组中
            title: res.data[i].title,
            id: res.data[i].id,
            addr: res.data[i].address,
            province: res.data[i].ad_info.province,
            city: res.data[i].ad_info.city,
            district: res.data[i].ad_info.district,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng
          });
        }
        self.setData({
          selectedId: 0,
          centerData: sug[0],
          nearList: sug,
        })
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        wx.hideLoading();
      }
    });
  },
  //点击选择地图下方列表某项
  chooseCenter: function (e) {
    var id = e.currentTarget.id;
    let name = e.currentTarget.dataset.name;
    for (var i = 0; i < this.data.nearList.length; i++) {
      if (i == id) {
        this.setData({
          selectedId: id,
          centerData: this.data.nearList[i],
          latitude: this.data.nearList[i].latitude,
          longitude: this.data.nearList[i].longitude,
        });
        return;
      }
    }
  },
  //确认选择地址
  selectedOk: function () {
    console.log(this.data.centerData)
    let { latitude, longitude, title, addr } = this.data.centerData;
    this.setData({
      latitude,
      longitude,
      address: addr + title,
      nearList: []
    })
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },
  tolist: function () {
    wx.navigateTo({
      url: "../list/index"
    });
  }
})